package com.xja.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.xja.exception.CustomException;
import com.xja.mapper.ArticleMapper;
import com.xja.model.entity.Article;
import com.xja.model.entity.Comment;
import com.xja.model.entity.CommentLike;
import com.xja.service.IArticleLikeService;
import com.xja.service.IArticleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author caijg
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    private final IArticleLikeService articleLikeService;

    @Override
    @Transactional
    public void delete(ArrayList<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new CustomException("文章不存在", 500);
        }

        // 1. 删除文章
        this.removeByIds(ids);

        // 2. 删除文章点赞记录
        if (CollUtil.isNotEmpty(ids)) {
            articleLikeService.update()
                    .in("article_id", ids)
                    .remove();
        }

        // 3. 删除文章评论记录
        List<Long> commentIds = Db.query(Comment.class)
                .in("article_id", ids)
                .list()
                .stream()
                .map(Comment::getId)
                .toList();

        if (CollUtil.isNotEmpty(commentIds)) {
            Db.update(Comment.class)
                    .in("id", commentIds)
                    .remove();

            // 4. 删除评论-点赞记录
            Db.update(CommentLike.class)
                    .in("comment_id", commentIds)
                    .remove();
        }
    }
}